package com.domain.service.impl;

import com.domain.common.Comments;
import com.domain.common.Result;
import com.domain.dao.*;
import com.domain.pojo.*;
import com.domain.service.LoginService;
import com.domain.service.UsersService;
import com.domain.utils.ArithmeticUtil;
import com.domain.utils.DateUtils;
import com.domain.utils.NotNullUtils;
import com.domain.utils.wyyx.IMSet;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class UsersServiceImpl implements UsersService {
  
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private PublishMapper publishMapper;
    @Autowired
    private PublishAcceptanceMapper publishAcceptanceMapper;

    @Autowired
    private UsersHelpMapper usersHelpMapper;

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private UsersFillterUsersMapper usersFillterUsersMapper;

    @Autowired
    private ContactsMapper contactsMapper;

    @Autowired
    private LoginService loginService;


    /**
     * 修改个人信息
     *
     * @param userId
     * @param nickName
     * @param image
     * @param name
     * @param gender
     * @param birthday
     * @param city
     * @param industry
     * @param personalLabel
     * @param headImage
     * @param request
     */
    @Override
    public Result editUserInfo(String userId, String nickName, String image, String name, String gender, String birthday, String city, String industry, String personalLabel, String headImage, HttpServletRequest request) throws IOException {
        Users user = new Users();
        user.setId(userId);
        if (NotNullUtils.isNotNullObject(nickName)) {
            user.setNickname(nickName);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        user.setImage(image);
        usersMapper.updateByPrimaryKeySelective(user);
        if (NotNullUtils.isNotNullObject(name)) {
            user.setName(name);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(gender)) {
            user.setGender(new Integer(gender));
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(birthday)) {
            user.setBirthday(DateUtils.strToDate(birthday, "yyyy-MM-dd"));
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(city)) {
            user.setCity(city);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(industry)) {
            user.setIndustry(industry);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(personalLabel)) {
            user.setPersonalLabel(personalLabel);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(headImage)) {
            user.setHeadImage(headImage);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        //更改im信息
        IMSet.updateUser(userId, name, headImage, "", "", "");
        Users users = usersMapper.selectByPrimaryKey(userId);
        Map<String, Object> map = loginService.checklogin(users.getPhone(), null);
        return Result.success("操作成功", map);
    }

    /**
     * 修改手机号码
     *
     * @param userId
     * @param newPhoneNum
     */
    @Override
    public Result changePhoneNum(String userId, String newPhoneNum) throws IOException {
        //判断手机号是否注册
        int resultCount = usersMapper.selectByPhone(newPhoneNum);
        if (resultCount > 0) {
            return Result.publicResult(Comments.ILLEGAL_ARGUMENT, "手机号已经注册！");
        }
        Users users = new Users();
        users.setId(userId);
        users.setPhone(newPhoneNum);
        usersMapper.updateByPrimaryKeySelective(users);
        return Result.success();
    }

    /**
     * 我的
     *
     * @param userId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getUsersPageInfo(String userId) {
        Map<String, Object> maps = new HashMap<>();
        Users user = usersMapper.selectByPrimaryKey(userId);
        maps.put("id", user.getId());
        maps.put("name", user.getName());
        maps.put("phone", user.getPhone());
        maps.put("gender", user.getGender());
        maps.put("birthday", DateUtils.dateToStr(user.getBirthday(), "yyyy-MM-dd"));
        maps.put("headImage", user.getHeadImage());
        maps.put("industry", user.getIndustry());
        maps.put("personalLabel", NotNullUtils.sliptList(user.getPersonalLabel()));
        maps.put("city", user.getCity());
        maps.put("imageios", NotNullUtils.sliptList(user.getImage()));
        maps.put("spectralValue", user.getSpectralValue());
        maps.put("token", user.getSpareOne());
        //获取我得发布条数
        List<Publish> publishes = publishMapper.selectPublishByUserId(user.getId());
        maps.put("userPublishSize", publishes.size());
        //获取我的帮忙条数
        List<Map<String, Object>> publishAcceptances = publishAcceptanceMapper.selectByUserId(user.getId());
        maps.put("userPublishAcceptancesSize", publishAcceptances.size());
        //获取我的帮转条数
        List<Map<String, Object>> helps = usersHelpMapper.selectByUsersId(user.getId());
        maps.put("userHelpSize", helps.size());
        return Result.success("操作成功", maps);
    }

    /**
     * 编辑我的发布
     *
     * @param userToken    用户token
     * @param userId       用户id
     * @param publishId    发布id
     * @param title        发布title
     * @param content      发布类容
     * @param images       发布照片
     * @param filterUserId 过滤得好友
     * @param longitude    发布位置经度
     * @param latitude     发布位置纬度
     * @param cityName     发布城市名称
     * @param itIsPaid     发布是否有偿
     * @param typeId       发布类型id
     * @return
     */
    @Override
    public Result editUsersPublish(String userToken, String userId, String publishId, String title, String content, String images, String filterUserId, String longitude, String latitude, String cityName, String itIsPaid, String typeId) {
        //修改我的发布
        Publish ps = new Publish();
        ps.setId(publishId);
        ps.setUpdateTime(new Date());
        ps.setUserId(userId);
        ps.setTitle(title);
        ps.setLongitude(longitude);
        ps.setLatitude(latitude);
        ps.setCityName(cityName);
        ps.setContent(content);
        ps.setImages(images);
        ps.setFilterUserId(filterUserId);
        ps.setItIsPaid(new Integer(itIsPaid));
        ps.setSpareOne(typeId);
        publishMapper.updateByPrimaryKeySelective(ps);
        return Result.success();
    }

    /**
     * 获取用户账单明细
     *
     * @param userId
     * @param startTime
     * @param endTime
     * @param pageNum
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getUserBillDetail(String userId, String startTime, String endTime, String pageNum, String pageSize) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("userId", userId);
        if (NotNullUtils.isNotNullObject(startTime)) {
            maps.put("startTime", startTime);
        }
        if (NotNullUtils.isNotNullObject(startTime)) {
            maps.put("endTime", endTime);
        }
        PageHelper.startPage(new Integer(pageNum), new Integer(pageSize));
        List<Bill> bills = billMapper.selectByUsersId(maps);
        Map<String, Object> map = new HashMap<>();
        PageInfo pageInfo = new PageInfo(bills);
        double out = 0;
        double put = 0;
        for (Bill b : bills) {
            //支出
            if (Comments.SERZERBAL_OUT.equals(b.getBillType())) {
                out = ArithmeticUtil.sub(out, b.getBillMoney().doubleValue());
            }
            //收入
            if (Comments.SERZERBAL_PUT.equals(b.getBillType())) {
                put = ArithmeticUtil.sub(out, b.getBillMoney().doubleValue());
            }
        }
        map.put("billList", pageInfo.getList());
        if (out > 0) {
            map.put("putMoney", String.valueOf(out));
        } else {
            map.put("putMoney", "0.00");
        }
        if (put > 0) {
            map.put("outMoney", String.valueOf(put));
        } else {
            map.put("outMoney", "0.00");
        }
        return Result.success("操作成功", map);
    }

    /**
     * 屏蔽好友
     *
     * @param userId         用户id
     * @param fillterUserIds 过滤得好友id
     * @return
     */
    @Override
    public Result fillterUsers(String userId, String fillterUserIds) {
        //屏蔽好友的id
        List<String> list = NotNullUtils.sliptList(fillterUserIds);
        for (String s : list
        ) {
            Contacts c = contactsMapper.selectByUsersIdAndFriendsId(userId, s);
            if (NotNullUtils.isNotNullObject(c)) {
                //更新通讯录状态
                c.setItisFillter(Comments.IT_IS_FILLTER_YES);
                c.setUpdateTime(new Date());
                c.setFillterType(Comments.FRIENDS_FILLTER);
                contactsMapper.updateByPrimaryKeySelective(c);
            }
        }
        return Result.success();
    }

    //判断是否是好友
    @Override
    public boolean itIsUsersFriends(String userId, String usersFridens) {
        List<Contacts> contacts = contactsMapper.selectByUsersIdAndType(userId);
        for (Contacts c : contacts
        ) {
            if (usersFridens.equals(c.getSpareTwo())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取人脉链关系
     *
     * @param usersId          用户id
     * @param publishUsersId   发布者  id(受理者id)
     * @param helpUsersId      帮转者id
     * @param connectionUserId 中间人id
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public List<Map<String, Object>> getUsersHumanChain(String usersId, String publishUsersId, String helpUsersId, String connectionUserId) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        //查看人的好友列表
        List<Contacts> usersC = contactsMapper.selectByUsersIdAndType(usersId);
        //帮转人的好友列表
        List<Contacts> usersHelps = contactsMapper.selectByUsersIdAndType(helpUsersId);
        //发布人好友列表
        List<Contacts> pubishs = contactsMapper.selectByUsersIdAndType(usersId);
        //帮转人信息
        Users usershelp = usersMapper.selectByPrimaryKey(helpUsersId);
        //查看人信息
        Users users = usersMapper.selectByPrimaryKey(usersId);
        //发布人信息
        Users publishUsers = usersMapper.selectByPrimaryKey(publishUsersId);
        //帮转人脉关系
        if (NotNullUtils.isNotNullObject(helpUsersId)) {
            Users select = usersMapper.selectByPrimaryKey(connectionUserId);
            //查看人的好友列表包含帮转人
            Map<String, Object> mapf = new HashMap<>();
            Map<String, Object> mapu = new HashMap<>();
            Map<String, Object> userMap = new HashMap<>();
            Map<String, Object> cmape = new HashMap<>();
            //发布人信息
            mapf.put("usersId", publishUsers.getId());
            mapf.put("userName", publishUsers.getName());
            mapf.put("userHead", publishUsers.getHeadImage());
            mapList.add(mapf);
            //帮转人信息
            mapu.put("usersId", usershelp.getId());
            mapu.put("userName", usershelp.getName());
            mapu.put("helps", "helps");
            mapu.put("userHead", usershelp.getHeadImage());
            mapList.add(mapu);
            //隔得人脉
            if (NotNullUtils.isNotNullObject(select)) {
                //帮转人信息
                cmape.put("usersId", select.getId());
                cmape.put("userName", select.getName());
                cmape.put("userHead", select.getHeadImage());
                mapList.add(cmape);
            }
            //用户信息
            userMap.put("usersId", users.getId());
            userMap.put("userName", "我");
            userMap.put("userHead", users.getHeadImage());
            mapList.add(userMap);
        }
        //一度好友关系
        if (NotNullUtils.isNotNullObject(connectionUserId) && !NotNullUtils.isNotNullObject(helpUsersId)) {
            Users select = usersMapper.selectByPrimaryKey(connectionUserId);
            Map<String, Object> mapf = new HashMap<>();
            Map<String, Object> mapu = new HashMap<>();
            Map<String, Object> userMap = new HashMap<>();
            //发布人信息
            mapf.put("usersId", publishUsers.getId());
            mapf.put("userName", publishUsers.getName());
            mapf.put("userHead", publishUsers.getHeadImage());
            mapList.add(mapf);
            //帮转人信息
            mapu.put("usersId", select.getId());
            mapu.put("userName", select.getName());
            mapu.put("userHead", select.getHeadImage());
            mapList.add(mapu);

            //用户信息
            userMap.put("usersId", users.getId());
            userMap.put("userName", "我");
            userMap.put("userHead", users.getHeadImage());
            mapList.add(userMap);
        }


        //直接好友关系
        if (!NotNullUtils.isNotNullObject(connectionUserId) && !NotNullUtils.isNotNullObject(helpUsersId)) {
            //获取好友信息
            Map<String, Object> mapf = new HashMap<>();
            Map<String, Object> mapu = new HashMap<>();
            //好友信息
            mapf.put("usersId", publishUsers.getId());
            mapf.put("userName", publishUsers.getName());
            mapf.put("userHead", publishUsers.getHeadImage());
            mapList.add(mapf);
            //用户信息
            mapu.put("usersId", users.getId());
            mapu.put("userName", "我");
            mapu.put("userHead", users.getHeadImage());
            mapList.add(mapu);
        }


      /*  //获取用户信息
        Users users = usersMapper.selectByPrimaryKey(usersId);
        //判断发布人是否是我的好友
        List<Contacts> cList = contactsMapper.selectByUsersIdAndType(usersId);
        for (Contacts c : cList
        ) {
            if (NotNullUtils.isNotNullObject(connectionUserId)) {
                //获取好友信息
                Users usersf = usersMapper.selectByPrimaryKey(publishUsersId);
                //中间人信息
                Users helpUsers = usersMapper.selectByPrimaryKey(connectionUserId);
                Map<String, Object> mapf = new HashMap<>();
                Map<String, Object> mapu = new HashMap<>();
                Map<String, Object> userMap = new HashMap<>();
                //发布人信息
                mapf.put("usersId", usersf.getId());
                mapf.put("userName", usersf.getName());
                mapf.put("userHead", usersf.getHeadImage());
                mapList.add(mapf);
                //帮转人信息
                mapu.put("usersId", helpUsers.getId());
                mapu.put("userName", helpUsers.getName());
                mapu.put("userHead", helpUsers.getHeadImage());
                mapList.add(mapu);

                //用户信息
                userMap.put("usersId", users.getId());
                userMap.put("userName", "我");
                userMap.put("userHead", users.getHeadImage());
                mapList.add(userMap);
            }
            if (NotNullUtils.isNotNullObject(helpUsersId)) {
                if (c.getSpareTwo().equals(helpUsersId)) {
                    //获取好友信息
                    Users usersf = usersMapper.selectByPrimaryKey(publishUsersId);
                    //帮转人信息
                    Users helpUsers = usersMapper.selectByPrimaryKey(helpUsersId);
                    Map<String, Object> mapf = new HashMap<>();
                    Map<String, Object> mapu = new HashMap<>();
                    Map<String, Object> userMap = new HashMap<>();
                    //发布人信息
                    mapf.put("usersId", usersf.getId());
                    mapf.put("userName", usersf.getName());
                    mapf.put("userHead", usersf.getHeadImage());
                    mapList.add(mapf);
                    //帮转人信息
                    mapu.put("usersId", helpUsers.getId());
                    mapu.put("userName", helpUsers.getName());
                    mapu.put("helps", "helps");
                    mapu.put("userHead", helpUsers.getHeadImage());
                    mapList.add(mapu);

                    //用户信息
                    userMap.put("usersId", users.getId());
                    userMap.put("userName", "我");
                    userMap.put("userHead", users.getHeadImage());
                    mapList.add(userMap);
                }
            } else {
                //直接好友关系
                if (c.getSpareTwo().equals(publishUsersId)) {
                    //获取好友信息
                    Users usersf = usersMapper.selectByPrimaryKey(c.getSpareTwo());
                    Map<String, Object> mapf = new HashMap<>();
                    Map<String, Object> mapu = new HashMap<>();
                    //好友信息
                    mapf.put("usersId", usersf.getId());
                    mapf.put("userName", usersf.getName());
                    mapf.put("userHead", usersf.getHeadImage());
                    mapList.add(mapf);
                    //用户信息
                    mapu.put("usersId", users.getId());
                    mapu.put("userName", "我");
                    mapu.put("userHead", users.getHeadImage());
                    mapList.add(mapu);
                }
            }*/

        /* }*/
        return mapList;
    }


}


